import React, { Fragment } from 'react';
import { Button, Descriptions, Drawer, Space, Table } from 'antd';
import { message } from 'antd/es';
import AddUser from './addUser';
import DeleteUser from './deleteUser';
import EditUser from './editUser';
import SearchUser from './searchUser';
import { fetchUsers } from '../../services/userServices';

class Demo2 extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      usertable: [],
      visible: false,
      reviseVisible: false,
      currentRecord: {},
    };
  }

  componentDidMount() {
    this.fetchTable();
  }

  fetchTable = async () => {
    try {
      const response = await fetchUsers();
      const { data = [] } = response;
      const { records = [] } = data;
      this.setState({ usertable: records });
    } catch (error) {
      message.error(error.message || 'Failed to fetch users');
    }
  };

  columns = [
    {
      title: '序号',
      key: 'index',
      render: (_, record, index) => (
        index + 1
      ),
    },
    {
      title: '部门代号',
      dataIndex: 'deptId',
      key: 'deptId',
    },
    {
      title: '部门名称',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '用户代号',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a href="#" onClick={() => this.handleOpenReviseDrawer(record)}>修改</a>
          <DeleteUser userId={record.userId} onDeleteSuccess={this.handleDeleteUser} />
        </Space>
      ),
    },
  ];

  // 修改后或者添加后后都会调用这个方法，更新表格
  handleOpenReviseDrawer = (data) => {
    console.log(data);
    this.setState({ reviseVisible: true });
    // 保存当前记录
    this.state.currentRecord = data;
    // 将修改后的数据作用于整个表格
    this.setState((prevState) => {
      const updatedTable = prevState.usertable.map((user) =>
        user.userId === data.userId ? data : user,
      );
      return { usertable: updatedTable };
    });
  };

  // 删除后调用这个方法，更新表格
  handleDeleteUser = (userId) => {
    this.setState((prevState) => {
      const updatedTable = prevState.usertable.filter(user => user.userId !== userId);
      return { usertable: updatedTable };
    });
  };

  handleOpenDrawer = () => {
    this.setState({ visible: true });
  };

  onClose = () => {
    this.setState({ visible: false });
  };

  onEditClose = () => {
    this.setState({ reviseVisible: false });
  };

  render() {
    return (
      <Fragment>
        <>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <Button type="primary" onClick={this.handleOpenDrawer}>
              新增
            </Button>
            <SearchUser />
          </div>
          <Drawer title="新增用户"
                  placement="right"
                  onClose={this.onClose}
                  width={'30%'}
                  open={this.state.visible}>
            <AddUser refreshPage={this.fetchTable} closeDrawer={this.onClose} />
          </Drawer>
          <Drawer title="修改用户"
                  placement="left"
                  onClose={this.onEditClose}
                  width={'30%'}
                  destroyOnClose={true}
                  open={this.state.reviseVisible}>
            <EditUser refreshPage={this.handleOpenReviseDrawer}
                      record={this.state.currentRecord}
                      closeDrawer={this.onEditClose} />
          </Drawer>
        </>
        <Table dataSource={this.state.usertable} columns={this.columns} />;
      </Fragment>
    );
  }
}

export default Demo2;
